<template>
  <div class="external-num">
    <div class="tool">
      <div class="" style="float: left">
        <span @click.stop="addSipNum" class="main-color"><i class="el-icon-plus"></i><span>添加</span></span>
        <span @click.stop="reshList" class="main-color margin-l-10"><i class="iconfont icon-shuaxin"></i><span>刷新</span></span>
        <el-input
          style="width: 300px"
          class="margin-l-10"
          size="mini"
          placeholder="请输入外显组名称进行查询"
          @keyup.native.enter="handlerClick"
          v-model.trim="query">
          <i
            class="el-input__icon el-icon-search"
            slot="suffix"
            @click="handlerClick">
          </i>
        </el-input>
      </div>
      <div class="pag-wapper" style="float: right">
        <pagination
          style="float: left"
          :small="true"
          :currentPage="currentPage"
          :count="count"
          @turnPage="trunPages"
          :totalPage="Math.ceil(count/10)">
        </pagination>
      </div>
    </div>
    <div class="table-wapper">
      <el-table
        :data="tableList"
        size="mini"
        highlight-current-row
        stripe
        style="width: 100%">
        <el-table-column label="外显号组名称"><template scope="scope">{{ scope.row.DisplayName }}</template></el-table-column>
        <el-table-column label="最后更新时间"><template scope="scope">{{ scope.row.UpdateTime }}</template></el-table-column>
        <el-table-column label="操作" width="150">
          <template scope="scope">
            <span :class="scope.row.Enable === true ? 'pink' : 'main-color'"
                  @click="handleStatus(scope.row)"
                  v-html="scope.row.Enable === true ? '停用' : '启用'">

            </span>
            <el-button type="text" class="margin-l-10" size="small" @click="handleEdit(scope.row)">{{$t('public.edit')}}</el-button>
            <el-button type="text" size="small" class="pink" @click="handleDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
<leftSlide :visible.sync='slideLeft' :title="operType === 'add' ? '添加外显号组' : '修改外显号组'" @saveClick="handleSaveCLick" @cancelClick="cancelClick" :showFooter="true">
  <div style="margin: 20px">
    <div class="prompt">温馨提示：外显号和输入座席工号以英文逗号或者回车隔开</div>
    <div class="margin-t-15">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" label-position="top">
        <el-form-item label="外显号组名称" prop="DisplayName">
          <el-input v-model.trim="form.DisplayName" :maxlength=10></el-input>
        </el-form-item>
        <el-form-item label="添加外显号" prop="NumberStr" class="margin-t-15">
          <el-input type="textarea" v-model="form.NumberStr"></el-input>
        </el-form-item>
        <el-row class="margin-t-15">
          <span>外显策略：</span>
          <el-radio-group v-model="form.Strategy">
            <el-radio label="random">随机</el-radio>
            <el-radio label="rrmemory">顺序</el-radio>
          </el-radio-group>
        </el-row>
        <div class="margin-t-15">
          <span>{{$t('public.pickAgent')}}：</span>
          <el-radio-group v-model="form.choiceType">
            <el-radio label="choise">选择</el-radio>
            <el-radio label="enter">输入</el-radio>
          </el-radio-group>
        </div>
        <div v-if="form.choiceType === 'choise'" style="margin-top: 7px">
          <AgentTreeSelect ref="agentTree" class="agent-tree" :PBX="pbx"
                           :agentCheckedIds="agentCheckedIds"
                           :forChannelConfig="true"
                           @agent-change="handleAgentChange"></AgentTreeSelect>
        </div>
        <div v-if="form.choiceType === 'enter'" style="margin-top: 7px">
          <el-input type="textarea" v-model="form.UserStr"></el-input>
        </div>
      </el-form>
    </div>
  </div>
</leftSlide>
  </div>
</template>
<script>
  import AgentTreeSelect from '@/components/public-modules/agent-tree/AgentTreeSelect.vue'
  import Agent from '@/components/public-modules/cache/Agent'
  import { deepClone, ivrSearch, handleFakePage } from '@/utils/m7Utils.js'
  import Pagination from '@/components/public-modules/card/Pagination'
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  export default {
    name: 'externalNum',
    data () {
      return {
        checkedAgentsOfChannelConfig: [],
        agentCheckedIds: [],
        rules: {
          DisplayName: { required: true, message: '请输入外显号组名称', trigger: 'blur' },
          NumberStr: { required: true, message: '请输入外显号', trigger: 'blur' }
        },
        form: {
          UserStr: '',
          DisplayName: '',
          NumberStr: '',
          Strategy: 'random',
          choiceType: 'choise'
        },
        operType: '',
        slideLeft: false,
        count: 0,
        currentPage: 1,
        query: '',
        dataList: [],
        selectAgent: [],
        currentObj: {},
        oldPBX: '',
        tableList: [],
        handledList: [],
        totalList: []
      }
    },
    components: {
      Agent,
      Pagination,
      leftSlide,
      AgentTreeSelect
    },
    watch: {
      pbx () {
        let routerName = this.$route.meta.title
        if (routerName === 'externalNum') {
          console.log('exter')
          this.reshList()
        }
      }
    },
    computed: {
      pbx () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    methods: {
      handleEdit (row) {
        this.operType = 'edit'
        this.slideLeft = true
        this.currentObj = row
        this.form = {
          DisplayName: row.DisplayName,
          NumberStr: row.NumberStr,
          Strategy: row.Strategy,
          UserStr: row.UserStr || '',
          choiceType: ''
        }
        if (row.IsWrite) {
          this.form.choiceType = 'enter'
          this.selectAgent = []
          this.agentCheckedIds = []
        } else {
          this.form.choiceType = 'choise'
          this.agentCheckedIds = deepClone(row.Users)
          this.selectAgent = deepClone(row.Users)
          this.UserStr = ''
        }
        this.$refs['form'].resetFields()
      },
      handleSaveCLick () {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.operType === 'add') {
              if (!this.handleAddSave()) {
                return false
              }
            } else if (this.operType === 'edit') {
              if (!this.handleEditSave()) {
                return false
              }
            }
          }
        })
      },
      handleEditSave () {
        let data = {
          _id: this.currentObj._id,
          Enable: this.currentObj.Enable,
          IsCover: false,
          IsWrite: false,
          DisplayName: this.form.DisplayName,
          NumberStr: this.form.NumberStr,
          Strategy: this.form.Strategy,
          Account: this.$store.state.session.account.account,
          PBX: this.pbx
        }
        if (this.form.choiceType === 'choise') {
          this.$refs.agentTree.handleCheckChange()
          let _array = []
          for (let i = 0; i < this.selectAgent.length; i++) {
            _array.push(this.selectAgent[i]._id)
          }
          data.Users = _array
          if (data.Users.length === 0) {
            this.$message.error(this.$t('report.pleChoseAgent'))
            return
          }
          data.UserStr = ''
        } else {
          data.IsWrite = true
          data.UserStr = this.form.UserStr
          if (data.UserStr === '') {
            this.$message.error('请输入座席！')
            return
          }
        }
        this.addOrUpdateDispath(data, '修改成功')
        return true
      },
      handleAddSave () {
        let data = {
          Enable: true,
          IsCover: false,
          IsWrite: false,
          DisplayName: this.form.DisplayName,
          NumberStr: this.form.NumberStr,
          Strategy: this.form.Strategy,
          Account: this.$store.state.session.account.account,
          PBX: this.pbx
        }
        if (this.form.choiceType === 'choise') {
          data.UserStr = ''
          let _array = []
          for (let i = 0; i < this.selectAgent.length; i++) {
            _array.push(this.selectAgent[i]._id)
          }
          data.Users = _array
          if (data.Users.length === 0) {
            this.$message.error(this.$t('report.pleChoseAgent'))
            return
          }
        } else {
          data.IsWrite = true
          data.UserStr = this.form.UserStr
          if (data.UserStr === '') {
            this.$message.error('请输入座席！')
            return
          }
        }
        this.addOrUpdateDispath(data, '添加成功')
        return true
      },
      addOrUpdateDispath (data, tip) {
        this.$store.dispatch('addOrUpdateCallerGroup', data).then(resp => {
          if (resp && resp.success) {
            this.cancelClick()
            this.$message.success(tip)
            this.reshList()
          } else {
            if (resp && resp.message === 'the_user_repeat') {
              this.$confirm('座席' + resp.repeat + '已设置过外显号组，是否替换成新的？', this.$t('public.tip'), {
                confirmButtonText: this.$t('public.confirm'),
                cancelButtonText: this.$t('public.cancel'),
                cancelButtonClass: 'primary_btn',
                confirmButtonClass: 'primary_btn',
                type: 'warning'
              }).then(() => {
                data.IsCover = true
                this.$store.dispatch('addOrUpdateCallerGroup', data).then((res) => {
                  if (res.success) {
                    this.cancelClick()
                    this.$message.success(tip)
                    this.reshList()
                  }
                })
              })
            }
          }
        })
      },
      cancelClick () {
        this.slideLeft = false
      },
      handleAgentChange (checkedAgents) {
        console.log(checkedAgents)
        this.selectAgent = checkedAgents
        let _array = []
        for (let i = 0; i < this.selectAgent.length; i++) {
          _array.push(this.selectAgent[i]._id)
        }
        this.agentCheckedIds = _array
      },
      handleStatus (row) {
        let data = {
          _id: row._id,
          Enable: !row.Enable,
          IsCover: row.IsCover
        }
        if (data.Enable === false) {
          this.$confirm('确定要停用吗？', this.$t('public.tip'), {
            confirmButtonText: this.$t('public.confirm'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('enableGroup', data).then((res) => {
              if (res.success) {
                this.$message.success('操作成功！')
                this.reshList()
              }
            })
          })
        } else {
          this.$store.dispatch('enableGroup', data).then(resp => {
            if (resp && resp.success) {
              this.$message.success('操作成功！')
              this.reshList()
            }
          })
        }
      },
      trunPages (val) {
        this.currentPage = val
        this.tableList = handleFakePage(this.currentPage, this.handledList)
      },
      addSipNum () {
        this.operType = 'add'
        this.slideLeft = true
        this.selectAgent = []
        this.agentCheckedIds = []
        this.form = {
          UserStr: '',
          DisplayName: '',
          NumberStr: '',
          Strategy: 'random',
          choiceType: 'choise'
        }
        this.$refs['form'].resetFields()
      },
      handlerClick () {
        this.handledList = ivrSearch(this.totalList, this.query, ['DisplayName']) || []
        this.count = this.handledList.length || 0
        this.currentPage = 1
        this.tableList = handleFakePage(this.currentPage, this.handledList)
      },
      fetchData () {
        this.$store.dispatch('queryGroups', {Account: this.$store.state.session.account.account, PBX: this.pbx}).then(resp => {
          if (resp && resp.success) {
            this.$store.commit('SET_IVRMAP_DETAIL', {PBX: this.pbx, typeName: 'ivr_node_callerGroup', data: resp.list || [], flag: 'data', node: this})
            this.query = ''
            this.currentPage = 1
            this.count = resp.list.length
            this.totalList = resp.list
            this.handledList = resp.list
            this.tableList = handleFakePage(this.currentPage, this.handledList)
          }
        })
      },
      reshList () {
        this.fetchData()
      },
      handleDel (row) {
        let that = this
        this.$confirm('确定要删除该条信息吗？', this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          let data = {
            _id: row._id,
            IsCover: row.IsCover
          }
          that.$store.dispatch('delGroup', data).then((res) => {
            if (res.success) {
              that.$message.success(this.$t('config.channel.deleteSuccess'))
              that.reshList()
            }
          })
        })
      }
    },
    deactivated () {
      this.oldPBX = this.pbx
    },
    activated () {
      if (this.oldPBX !== this.pbx) {
        this.reshList()
      }
    },
    beforeMount () {
      this.fetchData()
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .external-num
    margin 20px
    overflow-y hidden
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    overflow-y: auto;
    font-size: 12px;
    .margin-t-15
      margin-top 15px
    .margin-l-10
      margin-left 10px
    .pag-wapper
      position: absolute;
      right: 15px;
      top: 14px;
    .main-color
      color $c-main
      cursor pointer
    .wapper
      display flex
      flex-direction column
    .tool
      position relative
      border 1px solid #e7e7eb
      border-bottom 0
      padding  12px 15px
      /*display flex*/
      justify-content space-between
    .primary_btn
      padding 0px 10px
      min-width 60px
    .pink
      color $c-pink
      cursor pointer
    .prompt
      color $c-prompt
</style>

